/*
 * Created by SharpDevelop.
 * User: mac
 * Date: 16.07.2006
 * Time: 15:40
 * 
 * To change this template use Tools | Options | Coding | Edit Standard Headers.
 */

using System;
using CsGL.OpenGL;
using System.Drawing;
using System.Drawing.Imaging;

namespace TagTool.GraphicTypes
{

	[Serializable()]
	public class Texture : GL, IDisposable
	{

		private uint[] texture = new uint[1];	
		private String fileName = @"gradient_alpha.bmp";
		private int width;
		private int height;
		
		public Texture()
		{
			Load(fileName);
		}
		
		public int Width
		{
			get { return width; }
		}
		
		public int Height
		{
			get { return height; }
		}
		
		public Texture(String fileName)
		{
			FileName = fileName;
		}
		
		public virtual void Dispose()
		{
			if (glIsTexture(texture[0]) == GL_TRUE)
			{
				glDeleteTextures(1, texture);
				
			}
		}

		public String FileName
		{
			set 
			{
				if (!fileName.Equals(value))
				{
					fileName = value;	
					Load(fileName);
				}
			}
		}

		public void Apply()
		{
			glBindTexture(GL_TEXTURE_2D, texture[0]);
		}

		private void Load(string filename) 
		{
			Bitmap bitmap = null;														// The Bitmap Image For Our Texture
			System.Drawing.Rectangle rectangle;														// The Rectangle For Locking The Bitmap In Memory
			BitmapData bitmapData = null;

			// Load The Bitmap
			try {
				//bitmap = new Bitmap(filename);
				if (System.IO.File.Exists(filename))
				{
					bitmap = new Bitmap(filename);
					bitmap.RotateFlip(RotateFlipType.RotateNoneFlipY);						// Flip The Bitmap Along The Y-Axis
					rectangle = new System.Drawing.Rectangle(0, 0, bitmap.Width, bitmap.Height);			// Select The Whole Bitmap
	
					width = bitmap.Width;
					height = bitmap.Height;
	
					// Get The Pixel Data From The Locked Bitmap
					bitmapData = bitmap.LockBits(rectangle, ImageLockMode.ReadOnly, System.Drawing.Imaging.PixelFormat.Format24bppRgb);
	
					glGenTextures(1, texture);												// Create One Texture
	
					// Create Linear Filtered Texture
					glBindTexture(GL_TEXTURE_2D, texture[0]);
					glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
					glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); 
					glTexImage2D(GL_TEXTURE_2D, 0, (int) GL_RGB8, bitmap.Width, bitmap.Height, 0, GL_BGR_EXT, GL_UNSIGNED_BYTE, bitmapData.Scan0);
				}
			}
			catch (Exception ex)
			{
				String s = ex.Message;
			}
			finally 
			{
				if(bitmap != null) {
					bitmap.UnlockBits(bitmapData);										// Unlock The Pixel Data From Memory
					bitmap.Dispose();													// Clean Up The Bitmap
				}
			}
		}
	}
	
}
